/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("MES_UserPost",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions;
using VolPro.Core.ManageUser;
using VolPro.Core.Utilities;
using VolPro.Entity.DomainModels;
using VolPro.MES.IRepositories;
using VolPro.MES.IServices;

namespace VolPro.MES.Controllers
{
    public partial class MES_UserPostController
    {
        private readonly IMES_UserPostService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IMES_UserPostRepository _userpostRepository;
        [ActivatorUtilitiesConstructor]
        public MES_UserPostController(
            IMES_UserPostService service,
            IHttpContextAccessor httpContextAccessor,
            IMES_UserPostRepository userpostRepository
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
            _userpostRepository = userpostRepository;
        }
        /// <summary>
        /// 查询用户对应的工位/工序
        /// </summary>
        /// <returns></returns>
        //[HttpPost, Route("MES_UserPost"), AllowAnonymous]
        [HttpPost, Route("MES_UserFormProcess")]
        public async Task<IActionResult> MES_UserFormProcess()
        {
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                // 主要方法：从 HttpContext 的 Request 头部获取
                if (HttpContext.Request.Headers.TryGetValue("Authorization", out var authHeader))
                {
                    // 提取 Bearer Token
                    var token = authHeader.ToString().Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);

                    // 现在你拿到了 token 字符串
                    // 注意：通常你不需要直接使用这个字符串，因为认证中间件已经帮你解析验证过了。
                    // 这里获取通常是为了记录日志或传递到下层服务等特殊需求。

                    // ... 你的业务逻辑 ...
                }
                int userId = UserContext.Current.UserId;
                if (userId != 0)
                {

                    var listA = await _userpostRepository.DbContext.Set<MES_UserPost>().FirstOrDefaultAsync(b => b.UserId == userId);
                    if (listA == null) 
                    {
                        responseContent.Code = "300";
                        responseContent.OK($"{UserContext.Current.UserName}用户未分配工位/工序，请联系管理员", null);
                    }
                    else
                    {
                        var listB = await _userpostRepository.DbContext.Set<MES_Process>().FirstOrDefaultAsync(b => b.ProcessID.ToString() == listA.ProcessID);
                       
                        if (listB == null || string.IsNullOrEmpty(listB.ProcessID.ToString()))
                        {
                            responseContent.Code = "300";
                            responseContent.OK($"{UserContext.Current.UserName}用户未分配工位/工序，请联系管理员", null);
                        }
                        else
                        {
                            //string serializedJson = JsonConvert.SerializeObject(listB, Formatting.Indented); //列化，Formatting.Indented 使输出的JSON格式美观（有缩进和换行）
                            //string serializedJson = JsonConvert.SerializeObject(listB, Formatting.None);//序列化为紧凑格式
                            //string serializedJson = JsonConvert.SerializeObject(listB);
                            responseContent.Code = "200";
                            responseContent.OK("成功", listB);
                        }
                    }
                }
                else
                {
                    responseContent.Code = "301";
                    responseContent.OK("无此用户");
                }
            }
            catch (Exception ex)
            {
                responseContent.Code = "500";
                responseContent.Error(ex.Message);
            }
            return JsonNormal(responseContent);
        }
       
    }
}
